package com.ymatou.iapi.hunter.testcase;

import java.math.BigDecimal;

import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.hunter.paramater.GetHunterInfoReqest;
import com.ymatou.iapi.hunter.service.GetHunterInfoCall;
import com.ymatou.iapi.optrade.resp.Order;
import com.ymatou.iapi.optrade.resp.TradingServiceResp;
import com.ymatou.iapi.synctrade.service.TradingSyncService;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.tag.P1;
import com.ymttest.business.service.HunterCallService;
import com.ymttest.business.service.OrderCallService;
import com.ymttest.business.service.PayGateWayCallService;
import com.ymttest.business.service.YMTTrading.TradingCallService;
import com.ymttest.business.service.YMTTrading.TradingPlaceHunterOrderCallService;
import com.ymttest.database.model.hunter.HunterRelation;
import com.ymttest.database.sqlwapper.hunter.HunterRelationWrapper;
import com.ymttest.utils.DataUtil;

public class Ts_GetHunterInfo {
	
	private static GetHunterInfoReqest getHunterInfoReqest;
	private static GetHunterInfoCall getHunterInfoCall;

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("查看推手信息");
	}

	@Before
	public void caseUp() {
		getHunterInfoReqest = new GetHunterInfoReqest();
		getHunterInfoCall = new GetHunterInfoCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(getHunterInfoCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}
	
	public void verifyAllAncestryChildrenCount(long hunterId) {
		
		HunterRelationWrapper wrapper = new HunterRelationWrapper();
		HunterRelation hunterRelation = wrapper.selectByPrimaryKey(hunterId);
		
		long parentHunterId = hunterRelation.getParent_hunter_id();
		
		if (hunterRelation.getParent_hunter_id() != 0) {
			
			Logger.comment("验证父节点" + parentHunterId);
			Logger.verifyEquals(HunterCallService.countChildren(parentHunterId, true), 
					wrapper.selectByPrimaryKey(parentHunterId).getChildren_total(), 
					"验证父节点count");
			
			this.verifyAllAncestryChildrenCount(parentHunterId);
		}
	}
	
	public void verifyDb(long hunterId, JSONObject o) throws JSONException {
		
		HunterRelationWrapper wrapper = new HunterRelationWrapper();
		HunterRelation hunterRelation = wrapper.selectByPrimaryKey(hunterId);
		
		DataUtil.verify(o.getInt("hunterLevel"), hunterRelation.getHunter_level(),
				"验证hunterLevel");
		DataUtil.verify(o.getInt("hunterStatus"), hunterRelation.getStatus(),
				"验证hunterStatus");
		DataUtil.verifyDateEquals(o.getString("addTime"), hunterRelation.getAdd_time(),
				"验证addTime");
		DataUtil.verifyDateEquals(o.getString("code"), hunterRelation.getCode(),
				"验证code");
//		//接口返回的childrenTotal需要在数据库数据的基础上加1
//		DataUtil.verifyDateEquals(o.optInt("childrenTotal"), HunterCallService.countChildren(hunterId, true) + 1,
//				"验证childrenTotal");
		
		DataUtil.verifyDateEquals(
				o.optInt("childrenTotal"),
				hunterRelation.getChildren_total() == null ? 0 : hunterRelation
						.getChildren_total(), "验证childrenTotal");
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetHunterInfo_001() {
		Logger.start(true, "查询推手信息");
		try {
			
			// 创建订单
			Logger.comment("前置数据准备");
			
			OrderCallService orderCallService = new OrderCallService();
			int userId = orderCallService.createNewUser();
			long hunterId = 4321;
			
			//购买一个大礼包，成为一位推手，上级为hunterId
			TradingServiceResp placeOrder = TradingPlaceHunterOrderCallService
					.placeHunterOrder(hunterId, userId, 1);
			long tradingId = placeOrder.getTradingId();
			long orderId = placeOrder.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrder.getPayableAmount();

			Long thirdTradingId = TradingCallService.payOrder(userId,
					BigDecimal.ZERO, tradingId, "13");

			PayGateWayCallService.notifyCall("13", thirdTradingId.toString(),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId);
			
			Logger.comment("前置数据准备结束");
			
			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(3000);
			
			getHunterInfoReqest.setHunterId(userId);
			getHunterInfoCall.setData(getHunterInfoReqest);
			getHunterInfoCall.callService();
			
			Logger.verifyEquals("success", getHunterInfoCall.getResponseData().getString("resultMessage"),
					"验证resultMessage");
			Logger.verifyEquals(0, getHunterInfoCall.getResponseData().getInt("resultCode"),
					"验证resultCode");
			Logger.verifyEquals(true, getHunterInfoCall.getResponseData().getBoolean("success"),
					"验证success");
			
			verifyDb(userId, getHunterInfoCall.getResult());
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetHunterInfo_002() {
		Logger.start(true, "传入hunterId为0");
		try {

			getHunterInfoReqest.setHunterId(0);
			getHunterInfoCall.setData(getHunterInfoReqest);
			getHunterInfoCall.callService();
			
			Logger.verifyEquals("hunterId:推手用户编号不能为空", getHunterInfoCall
					.getResponseData().getString("resultMessage"),
					"验证resultMessage");
			Logger.verifyEquals(2,
					getHunterInfoCall.getResponseData().getInt("resultCode"),
					"验证resultCode");
			Logger.verifyEquals(false, getHunterInfoCall.getResponseData()
					.getBoolean("success"), "验证success");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetHunterInfo_003() {
		Logger.start(true, "传入不存在的hunterId");
		try {

			getHunterInfoReqest.setHunterId(2131421415123L);
			getHunterInfoCall.setData(getHunterInfoReqest);
			getHunterInfoCall.callService();
			
			Logger.verifyEquals("推手不存在！", getHunterInfoCall.getResponseData().getString("resultMessage"),
					"验证resultMessage");
			Logger.verifyEquals(3, getHunterInfoCall.getResponseData().getInt("resultCode"),
					"验证resultCode");
			Logger.verifyEquals(false, getHunterInfoCall.getResponseData().getBoolean("success"),
					"验证success");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetHunterInfo_004() {
		Logger.start(true, "查询被封锁的推手信息");
		try {
			
			// 创建订单
			Logger.comment("前置数据准备");
			
			OrderCallService orderCallService = new OrderCallService();
			int userId = orderCallService.createNewUser();
			long hunterId = 4321;
			TradingServiceResp placeOrder = TradingPlaceHunterOrderCallService
					.placeHunterOrder(hunterId, userId, 1);
			long tradingId = placeOrder.getTradingId();
			long orderId = placeOrder.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrder.getPayableAmount();

			Long thirdTradingId = TradingCallService.payOrder(userId,
					BigDecimal.ZERO, tradingId, "13");

			PayGateWayCallService.notifyCall("13", thirdTradingId.toString(),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId);
			
			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(3000);
			
			//封掉hunter
			HunterCallService.updateHunter(userId, 1);
			
			Logger.comment("前置数据准备结束");
			
			getHunterInfoReqest.setHunterId(userId);
			getHunterInfoCall.setData(getHunterInfoReqest);
			getHunterInfoCall.callService();
			
			Logger.verifyEquals("success", getHunterInfoCall.getResponseData().getString("resultMessage"),
					"验证resultMessage");
			Logger.verifyEquals(0, getHunterInfoCall.getResponseData().getInt("resultCode"),
					"验证resultCode");
			Logger.verifyEquals(true, getHunterInfoCall.getResponseData().getBoolean("success"),
					"验证success");
			
			verifyDb(userId, getHunterInfoCall.getResult());
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetHunterInfo_005() {
		Logger.start(true, "查询城市合伙人信息");
		try {
			//20324891为数据库写死的金牌合伙人
			getHunterInfoReqest.setHunterId(20324891);
			getHunterInfoCall.setData(getHunterInfoReqest);
			getHunterInfoCall.callService();
			
			Logger.verifyEquals("success", getHunterInfoCall.getResponseData().getString("resultMessage"),
					"验证resultMessage");
			Logger.verifyEquals(0, getHunterInfoCall.getResponseData().getInt("resultCode"),
					"验证resultCode");
			Logger.verifyEquals(true, getHunterInfoCall.getResponseData().getBoolean("success"),
					"验证success");
			
			verifyDb(20324891, getHunterInfoCall.getResult());
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	@Ignore
	public void Tc_GetHunterInfo_006() {
		Logger.start(true, "购买大礼包之后，验证所有祖先节点的childrenTotal");
		try {
			
			// 创建订单
			Logger.comment("前置数据准备");
			
			OrderCallService orderCallService = new OrderCallService();
			int userId = orderCallService.createNewUser();
			long hunterId = 4321;
			
			//购买一个大礼包，成为一位推手，上级为hunterId
			TradingServiceResp placeOrder = TradingPlaceHunterOrderCallService
					.placeHunterOrder(hunterId, userId, 1);
			long tradingId = placeOrder.getTradingId();
			long orderId = placeOrder.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrder.getPayableAmount();

			Long thirdTradingId = TradingCallService.payOrder(userId,
					BigDecimal.ZERO, tradingId, "13");

			PayGateWayCallService.notifyCall("13", thirdTradingId.toString(),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId);
			
			Logger.comment("前置数据准备结束");
			
			TradingSyncService.getSyncResult(orderId);
			
			getHunterInfoReqest.setHunterId(hunterId);
			getHunterInfoCall.setData(getHunterInfoReqest);
			getHunterInfoCall.callService();
			
			Logger.verifyEquals("success", getHunterInfoCall.getResponseData().getString("resultMessage"),
					"验证resultMessage");
			Logger.verifyEquals(0, getHunterInfoCall.getResponseData().getInt("resultCode"),
					"验证resultCode");
			Logger.verifyEquals(true, getHunterInfoCall.getResponseData().getBoolean("success"),
					"验证success");
			
			this.verifyAllAncestryChildrenCount(userId);
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetHunterInfo_007() {
		Logger.start(true, "hunter下面没有任何children");
		try {
			
			long hunterId = HunterCallService.buildHunterRelation(1, 1, 0).get(0);
			
			getHunterInfoReqest.setHunterId(hunterId);
			getHunterInfoCall.setData(getHunterInfoReqest);
			getHunterInfoCall.callService();
			
			Logger.verifyEquals("success", getHunterInfoCall.getResponseData().getString("resultMessage"),
					"验证resultMessage");
			Logger.verifyEquals(0, getHunterInfoCall.getResponseData().getInt("resultCode"),
					"验证resultCode");
			Logger.verifyEquals(true, getHunterInfoCall.getResponseData().getBoolean("success"),
					"验证success");
			
			this.verifyDb(hunterId, getHunterInfoCall.getResult());
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetHunterInfo_008() {
		Logger.start(true, "推手只购买一次大礼包，取消订单，推手状态为废弃");
		try {
			
			// 创建订单
			Logger.comment("前置数据准备");
			
			OrderCallService orderCallService = new OrderCallService();
			int userId = orderCallService.createNewUser();

			long hunterId = 1022;
			int hunterOrderType = 1;
			TradingServiceResp placeOrder = TradingPlaceHunterOrderCallService
					.placeHunterOrder(hunterId, 100, userId, hunterOrderType, false, false);
			Order order = placeOrder.getOrderList().get(0);
			long orderId = order.getOrderId();
			long tradingId = placeOrder.getTradingId();
			BigDecimal totalPrice = placeOrder.getPayableAmount();

			Long thirdTradingId = TradingCallService.payOrder(userId,
					BigDecimal.ZERO, tradingId, "13");

			PayGateWayCallService.notifyCall("13", thirdTradingId.toString(),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId);
			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(10000);

			// 生成管理费结算明细
			HunterCallService.onHunterRelationSearchedForManageFee(orderId,
					hunterId);

			HunterCallService.hunterOrderRefund(order, true, 0);

			Thread.sleep(4000);

			// 支付网关退款回调
			PayGateWayCallService.refundNotifyCall("13",
					thirdTradingId.toString(), userId);

			Thread.sleep(3000);

			Logger.comment("前置数据准备结束");
			
			getHunterInfoReqest.setHunterId(userId);
			getHunterInfoCall.setData(getHunterInfoReqest);
			getHunterInfoCall.callService();
			
			HunterRelationWrapper hunterRelationWrapper = new HunterRelationWrapper();
			HunterRelation hunterRelation = hunterRelationWrapper.selectByPrimaryKey((long)userId);
			
			Logger.verifyEquals(1, hunterRelation.getStatus(), "验证status");
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetHunterInfo_009() {
		Logger.start(true, "推手购买多次大礼包，全部取消订单，推手状态为废弃");
		try {
			
			// 创建订单
			Logger.comment("前置数据准备");
			
			OrderCallService orderCallService = new OrderCallService();
			int userId = orderCallService.createNewUser();

			long hunterId = 1022;
			int hunterOrderType = 1;
			
			for (int i = 0; i < 3; i++) {
				
				TradingServiceResp placeOrder = TradingPlaceHunterOrderCallService
						.placeHunterOrder(hunterId, 100, userId, hunterOrderType, false, false);
				Order order = placeOrder.getOrderList().get(0);
				long orderId = order.getOrderId();
				long tradingId = placeOrder.getTradingId();
				BigDecimal totalPrice = placeOrder.getPayableAmount();

				Long thirdTradingId = TradingCallService.payOrder(userId,
						BigDecimal.ZERO, tradingId, "13");

				PayGateWayCallService.notifyCall("13", thirdTradingId.toString(),
						totalPrice.subtract(BigDecimal.ZERO).toString(),
						userId);
				TradingSyncService.getSyncResult(orderId);
				Thread.sleep(10000);

				// 生成管理费结算明细
				HunterCallService.onHunterRelationSearchedForManageFee(orderId,
						hunterId);

				HunterCallService.hunterOrderRefund(order, true, 0);

				Thread.sleep(4000);

				// 支付网关退款回调
				PayGateWayCallService.refundNotifyCall("13",
						thirdTradingId.toString(), userId);

				Thread.sleep(3000);
			}

			Logger.comment("前置数据准备结束");
			
			HunterRelationWrapper hunterRelationWrapper = new HunterRelationWrapper();
			HunterRelation hunterRelation = hunterRelationWrapper.selectByPrimaryKey((long)userId);
			
			Logger.verifyEquals(1, hunterRelation.getStatus(), "验证status");
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetHunterInfo_010() {
		Logger.start(true, "推手购买多次大礼包，取消最后一笔订单，推手状态为正常");
		try {
			
			// 创建订单
			Logger.comment("前置数据准备");
			
			OrderCallService orderCallService = new OrderCallService();
			int userId = orderCallService.createNewUser();

			long hunterId = 1022;
			int hunterOrderType = 1;
			
			//购买两次大礼包
			for (int i = 0; i < 2; i++) {
				
				TradingServiceResp placeOrder = TradingPlaceHunterOrderCallService
						.placeHunterOrder(hunterId, 100, userId, hunterOrderType, false, false);
				Order order = placeOrder.getOrderList().get(0);
				long orderId = order.getOrderId();
				long tradingId = placeOrder.getTradingId();
				BigDecimal totalPrice = placeOrder.getPayableAmount();

				Long thirdTradingId = TradingCallService.payOrder(userId,
						BigDecimal.ZERO, tradingId, "13");

				PayGateWayCallService.notifyCall("13", thirdTradingId.toString(),
						totalPrice.subtract(BigDecimal.ZERO).toString(),
						userId);
				TradingSyncService.getSyncResult(orderId);
				Thread.sleep(10000);

				// 生成管理费结算明细
				HunterCallService.onHunterRelationSearchedForManageFee(orderId,
						hunterId);
			}
			
			//购买大礼包并取消
			TradingServiceResp placeOrder = TradingPlaceHunterOrderCallService
					.placeHunterOrder(hunterId, 100, userId, hunterOrderType, false, false);
			Order order = placeOrder.getOrderList().get(0);
			long orderId = order.getOrderId();
			long tradingId = placeOrder.getTradingId();
			BigDecimal totalPrice = placeOrder.getPayableAmount();

			Long thirdTradingId = TradingCallService.payOrder(userId,
					BigDecimal.ZERO, tradingId, "13");

			PayGateWayCallService.notifyCall("13", thirdTradingId.toString(),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId);
			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(10000);

			// 生成管理费结算明细
			HunterCallService.onHunterRelationSearchedForManageFee(orderId,
					hunterId);
			
			HunterCallService.hunterOrderRefund(order, true, 0);

			Thread.sleep(4000);

			// 支付网关退款回调
			PayGateWayCallService.refundNotifyCall("13",
					thirdTradingId.toString(), userId);

			Thread.sleep(3000);

			Logger.comment("前置数据准备结束");
			
			HunterRelationWrapper hunterRelationWrapper = new HunterRelationWrapper();
			HunterRelation hunterRelation = hunterRelationWrapper.selectByPrimaryKey((long)userId);
			
			Logger.verifyEquals(0, hunterRelation.getStatus(), "验证status");
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	public static void main(String[] args) {
		System.out.println(HunterCallService.countChildren(4321, true));
	}
}
